﻿using Microsoft.Practices.Unity;
using System.Reflection;
using System.Collections.Generic;

namespace OS.GenericDashboardViewer.Infrastructure
{
    public class UnitySingleton
    {
        public static UnitySingleton Instance = new UnitySingleton();
        IUnityContainer _unityContainer;

        private UnitySingleton() 
        {
            _unityContainer = new UnityContainer();
            ReplaceBehaviourExtensionsWithSafeExtension(_unityContainer);
        }

        private static void ReplaceBehaviourExtensionsWithSafeExtension(IUnityContainer container)
        {
            var extensionsField = container.GetType().GetField("extensions", BindingFlags.Instance | BindingFlags.NonPublic);
            var extensionsList = (List<UnityContainerExtension>)extensionsField.GetValue(container);
            var existingExtensions = extensionsList.ToArray();
            container.RemoveAllExtensions();

            container.AddExtension(new UnitySafeBehaviorExtension());
            foreach (var extension in existingExtensions)
            {
                if (!(extension is UnityDefaultBehaviorExtension))
                {
                    container.AddExtension(extension);
                }
            }
        }

        public IUnityContainer UnityContainer
        {
            get { return _unityContainer; }
            set { _unityContainer = value; }
        }
    }
}
